<template>
  <div class="components-container">
    <h1 style="margin-bottom: 10px">
      <span>摄像头案例</span>
    </h1>
    <video id="video" autoplay controls ref="myVideo"></video>
    <div class="btn-group">
      <el-button @click="openCamera">打开摄像头</el-button>
      <el-button @click="closeCamera">关闭摄像头</el-button>
      <el-button @click="snapShot">截屏</el-button>
      <el-button @click="downloadCamera">下载录制的内容</el-button>
    </div>
  </div>
</template>
<script>
import { defineComponent, reactive, ref, toRefs } from "vue";
import { ElMessage } from "element-plus";
export default defineComponent({
  setup() {
    const video = ref(null);
    const constraints = (window.constraints = {
      audio: false,
      video: true,
    });
    const state = reactive({
      isSnap:false,
      videoTracks: null,
      stream: null,
    });
    const openCamera = async (e) => {
      state.isSnap=true
      try {
        const stream = await navigator.mediaDevices.getUserMedia(constraints);
        handleSuccess(stream);
      } catch (e) {
        handleError(e);
      }
    };

    const handleSuccess = (stream) => {
      state.stream = stream;
      let tmpV = document.getElementById("video");
      state.videoTracks = stream.getVideoTracks();
      console.log(state.videoTracks);
      console.log("使用的设备是:" + state.videoTracks[0].label);
      window.stream = stream;
      video.src = stream;
      tmpV.srcObject = stream;
    };

    const handleError = (error) => {
      if (error.name === "ConstraintNotSatisfiedError") {
        const v = constraints.video;
        ElMessage.error(`宽:${v.width.exact}高:${v.height.exact}`);
      } else if (error.name === "PermissionDeniedError") {
        ElMessage.error("没有麦克风和摄像头的使用权限,请点击允许按钮");
      }
      ElMessage.error("getUserMedia错误,请点击允许按钮");
    };

    const closeCamera = () => {
      state.isSnap=false
      state.videoTracks[0].stop();
    };

    const snapShot = () => {
      if(!state.isSnap){
        ElMessage.info("不能截屏")
        return ;
      }
      const canvas=document.createElement('canvas')
      const a=document.createElement('a')
      const ctx=canvas.getContext('2d')
      const video=document.querySelector('#video')
      canvas.width=1000;
      canvas.height=1000;
      ctx.drawImage(video,0,0)
      let url=canvas.toDataURL('image/jpg')
      a.download=new Date().toLocaleString()
      a.href=url
      a.click()
      document.body.removeChild(a);
    };

    const downloadCamera = () => {
      let fileName = new Date().toLocaleString()+".mp4";
      let blob = new Blob([state.stream || null]);
      let downloadElement = document.createElement("a");
      let href = window.URL.createObjectURL(blob);
      downloadElement.srcObject=stream
      downloadElement.href = href;
      downloadElement.download = fileName;
      document.body.appendChild(downloadElement);
      downloadElement.click(); //点击下载
      document.body.removeChild(downloadElement); //下载完成移除元素
      window.URL.revokeObjectURL(href); //释放掉blob对象
    };
    return {
      ...toRefs(state),
      openCamera,
      closeCamera,
      snapShot,
      downloadCamera,
      video,
    };
  },
});
</script>

<style scoped>
/* 这里是实际RTC部分抽离组件分析 */
.components-container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
#video {
  box-sizing: border-box;
  padding: 0 10px;
  width: 100%;
  height: 500px;
}
.btn-group {
  display: flex;
  flex-direction: row;
  margin-top: 10px;
}
</style>
